package io.dy.guarded_extend;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author dmj
 * @date 2024年03月22日 下午4:55
 */
public class GuardedContainer<Res> {

    private static volatile GuardedContainer<?> instance = null;

    private final Map<Integer,GuardedObject<Res>> guardedContainer = new ConcurrentHashMap<>();

    private int id = 1;


    private GuardedContainer() {}

    public static<Res> GuardedContainer<Res> getInstance(){
        //DCL机制 双重检查机制
        if (instance == null) {
            synchronized (GuardedContainer.class){
                if(instance == null){
                    instance = new GuardedContainer<Res>();
                }
            }
        }
        return (GuardedContainer<Res>) instance;
    }


    /**
     * 生成ID
     * @return
     */
    private synchronized int generateId(){
        return id ++;
    }

    /**
     * 生产 GuardedObject
     * @return
     */
    public GuardedObject<Res> createGuardedObject(){
        int id = generateId();
        GuardedObject<Res> go = new GuardedObject<>(id);
        guardedContainer.put(id,go);
        return go;
    }

    /**
     * 根据ID 获取 GuardedObject
     * @param id
     * @return
     */
    public GuardedObject<Res> getById(Integer id){
        return guardedContainer.remove(id);
    }

    /**
     * 获取所有键集合
     * @return
     */
    public Set<Integer> getIds(){
        return guardedContainer.keySet();
    }
}
